#include <iostream>  
// #include <stdio.h>
// #include <fstream>

#include <string>
#include <opencv2/opencv.hpp>  
#include <opencv2/core/core.hpp>
#include <opencv2/core/mat.hpp>
using namespace std;  
using namespace cv;  
int fingerprint(Mat src, Mat* hash);

int main()
{
    Mat src = imread("/home/swls/下载/image_test/0.jpg", 0); 
    if(src.empty())
    {
        cout << "the image is not exist" << endl;  
        return -1;
    }
    Mat srchash, dsthash;
    fingerprint(src, &srchash);
    
        string path = "/home/swls/下载/image_test/19.bmp";
        Mat dst = imread(path, 0);  
        if(dst.empty())
        {
            cout << "the image is not exist" << endl;  
            return -1;
        }
        fingerprint(dst, &dsthash);
        int d = 0;
        for (int n = 0; n < srchash.size[1]; n++)
            if (srchash.at<uchar>(0,n) != dsthash.at<uchar>(0,n)) d++;  

        cout <<"  distance=  " <<d<<"\n";  
    


    return 0;
}


int fingerprint(Mat src, Mat* hash)
{
    resize(src, src, Size(32, 32));
    src.convertTo(src, CV_32F);
    Mat srcDCT; 
    dct(src, srcDCT);
    srcDCT = abs(srcDCT);
    double sum = 0;
    for (int i = 0; i < 8; i++)
        for (int j = 0; j < 8; j++)
            sum += srcDCT.at<float>(i,j);

    double average = sum/64;
    Mat phashcode= Mat::zeros(Size(8, 8), CV_8U);
    for (int i = 0; i < 8; i++)
        for (int j = 0; j < 8; j++)
            phashcode.at<char>(i,j) = srcDCT.at<float>(i,j) > average ? 1:0;

    *hash = phashcode.reshape(0,1).clone();
    return 0;
}


int nCount = 0;
    Mat src = imread("/home/swls/桌面/tes/mosi37.png", 0); 
    if(src.empty())
    {
        cout << "the image is not exist" << endl;  
        return -1;
    }

    string path = "/home/swls/桌面/tes/mosi38.png";
        Mat dst = imread(path, 0);  
        if(dst.empty())
        {
            cout << "the image is not exist" << endl;  
            return -1;
        }
    Mat src_bin, dst_bin;
    src_bin = Mat(src.size(), CV_8UC1);
    //直方图均衡化
    equalizeHist(src, src_bin);
    dst_bin= Mat(dst.size(), CV_8UC1);
    //直方图均衡化
    equalizeHist(dst, dst_bin);
    // threshold(src, src_bin, 128, 255,CV_THRESH_BINARY); 
    // threshold(dst, dst_bin, 128, 255,CV_THRESH_BINARY); 
    imwrite("src_bin.png",src_bin);
    imwrite("dst_bin.png",dst_bin);
    string str1 = pHashValue(src_bin);
    string str2 = pHashValue(dst_bin);
        for (int i = 0; i < 64; ++i)
        {
            if (str1[i] == str2[i])
            {
                nCount++;
            }
        }
    cout << nCount << endl;